package com.lry.web.cartoon.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lry.web.cartoon.entity.CartoonVariable;
import com.lry.web.cartoon.mapper.CartoonVariableMapper;
import com.lry.web.cartoon.processor.CartoonVerifyProcessor;
import com.lry.web.cartoon.service.CartoonVariableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Spider;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartoonVariableServiceImpl implements CartoonVariableService {
    @Autowired
    CartoonVariableMapper cartoonVariableMapper;



    public int setCartoonVariable(CartoonVariable cartoonVariable) {
        int insert = cartoonVariableMapper.insert(cartoonVariable);
        return insert;
    }


    public List<CartoonVariable> getCartoonVariables() {
        return cartoonVariableMapper.selectList(null);
    }

    public int delete(Integer id) {
        return cartoonVariableMapper.deleteById(id);
    }

    public CartoonVariable getCartoonVariable(Integer id) {
        return cartoonVariableMapper.selectById(id);
    }
    //获取全部小说规则，分页
    public Map<String, Object> selectCartoonVariables(Integer from, Integer size) {
        Page<CartoonVariable> page = new Page<CartoonVariable>(from,size);
        cartoonVariableMapper.selectPage(page, null);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("cartoonVariables",page.getRecords());
        map.put("pages",page.getPages());
        return map;
    }

    public int updateCartoonVariable(CartoonVariable cartoonVariable) {

        return cartoonVariableMapper.updateById(cartoonVariable);
    }

    public Map<String, Object> verifyCartoonVariable(CartoonVariable cartoonVariable, String name) throws Exception {
        Map<String,Object> map  = new HashMap<String,Object>();
        Spider.create(new CartoonVerifyProcessor(cartoonVariable,map))
                //设置爬取数据的地址
                .addUrl(cartoonVariable.getSearchUrl()+name)
                //执行爬虫
                .thread(5)
                .run();
        return map;
    }

}
